#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <poll.h>
#include <errno.h>

#define PORT 8888          // 服务器端口
#define MAX_CLIENTS 100     // 最大客户端连接数
#define BUFFER_SIZE 1024    // 缓冲区大小

int main() {
    int server_fd, client_fd;
    struct sockaddr_in server_addr, client_addr;
    struct pollfd fds[MAX_CLIENTS + 1];  // 包括服务器和客户端的文件描述符
    int client_sockets[MAX_CLIENTS];    // 保存客户端套接字
    char buffer[BUFFER_SIZE];
    socklen_t addr_len;

    // 初始化客户端套接字列表
    for (int i = 0; i < MAX_CLIENTS; i++) {
        client_sockets[i] = 0;
    }

    // 创建服务器套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }

    // 设置服务器地址结构
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(PORT);

    // 绑定服务器地址和端口
    if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("bind failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }

    // 监听端口
    if (listen(server_fd, 5) < 0) {
        perror("listen failed");
        close(server_fd);
        exit(EXIT_FAILURE);
    }
    printf("服务器启动，监听端口 %d\n", PORT);

    // 初始化 pollfd 结构
    fds[0].fd = server_fd;
    fds[0].events = POLLIN;  // 服务器套接字监听读事件
    for (int i = 1; i <= MAX_CLIENTS; i++) {
        fds[i].fd = -1;  // 初始化为无效描述符
        fds[i].events = 0;
    }

    while (1) {
        // 使用 poll 检查活动套接字
        int activity = poll(fds, MAX_CLIENTS + 1, -1);  // 无限等待
        if (activity < 0) {
            perror("poll error");
            continue;
        }

        // 检查是否有新的连接
        if (fds[0].revents & POLLIN) {
            addr_len = sizeof(client_addr);
            if ((client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &addr_len)) < 0) {
                perror("accept failed");
                continue;
            }

            // 打印新连接信息
            printf("新连接: 套接字 %d, IP: %s, 端口: %d\n",
                   client_fd, inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));

            // 添加新连接到 pollfd 列表
            for (int i = 1; i <= MAX_CLIENTS; i++) {
                if (fds[i].fd == -1) {
                    fds[i].fd = client_fd;
                    fds[i].events = POLLIN | POLLOUT;  // 监听读写事件
                    client_sockets[i - 1] = client_fd;
                    break;
                }
            }
        }

        // 处理客户端消息
        for (int i = 1; i <= MAX_CLIENTS; i++) {
            if (fds[i].fd != -1 && (fds[i].revents & POLLIN)) {
                int sd = fds[i].fd;
                int bytes_read = read(sd, buffer, BUFFER_SIZE);
                if (bytes_read == 0) {
                    // 客户端断开连接
                    addr_len = sizeof(client_addr);
                    getpeername(sd, (struct sockaddr *)&client_addr, &addr_len);
                    printf("客户端断开: IP: %s, 端口: %d\n",
                           inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
                    close(sd);
                    fds[i].fd = -1;
                    client_sockets[i - 1] = 0;
                } else {
                    // 处理收到的数据
                    buffer[bytes_read] = '\0';
                    printf("来自套接字 %d 的消息: %s\n", sd, buffer);

                    // 如果可写，回显消息给发送方
                    if (fds[i].revents & POLLOUT) {
                        if (send(sd, buffer, bytes_read, 0) < 0) {
                            perror("send error");
                        }
                    } else {
                        printf("套接字 %d 不可写，无法发送数据\n", sd);
                    }
                }
            }
        }
    }

    return 0;
}
